package cn.lijigou.shopping.service;

import android.content.Context;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import cn.lijigou.shopping.domain.MLocation;
import cn.lijigou.shopping.util.Util;

import com.mapbar.android.location.CellLocationProvider;

/**
 * @author 董永健 E-mail:dong_yong_jian@163.com
 * @version 创建时间：2012-4-11 下午05:04:42 类说明
 */
public class LocationMapBar implements LocationListener {
	private int changeSize = 0;
	private CellLocationProvider mCellLocationProvider = null;
	private Context mContext = null;
	private double lastLng;
	private double lastLat;
	private String city;
	private String address;

	public LocationMapBar(Context context) {
		this.mContext = context;
	}

	public void start() {
		mCellLocationProvider = new CellLocationProvider(mContext);
		mCellLocationProvider.addLocationListener(this);
		mCellLocationProvider.enableLocation();
		
		SharedPreferences sp = mContext.getSharedPreferences("info",Context.MODE_PRIVATE);
		lastLng = Double.parseDouble(sp.getString("LBSlng", "0.0"));
		lastLat = Double.parseDouble(sp.getString("LBSlat", "0.0"));
		city = sp.getString("city", "北京");
		address = sp.getString("address", "北京海淀");
	}

	public void stop() {
		mCellLocationProvider.disableLocation();
		mCellLocationProvider.clearLocationListener();
	}

	
	public void onLocationChanged(Location location) {
		/*获得上次启动定位和本次定位距离*/
		double distance = Util.getDistance(lastLat,lastLng, location.getLatitude(), location.getLongitude());
		/*如果距离不为零则使用次坐标*/
		if(distance!=0){
			if (location != null) {
				this.stop();
				Bundle bundle = location.getExtras();
				if (bundle != null) {
					String city = bundle.getString("city");
					String address = bundle.getString("address");

					MLocation  mLocation = new MLocation(location.getLatitude(), location
							.getLongitude(), city, address);

					LocationService.locations.put("mapbar", mLocation);
					LocationService.select();
				}
			}
		/*如果距离为零超过三次，则使用上次启动定位的坐标*/
		}else{
			changeSize++;
			if (changeSize >= 3) {
				this.stop();
				LocationGps gps = new LocationGps(mContext);
				gps.start();
			}
		}
	}

	
	public void onProviderDisabled(String provider) {

	}

	
	public void onProviderEnabled(String provider) {

	}

	
	public void onStatusChanged(String provider, int status, Bundle extras) {

	}

}
